package com.sun.showcase.exception;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import com.sun.showcase.pojo.Result;
@RestControllerAdvice
public class GlobalExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    public static final String DEFAULT_ERROR_VIEW = "exception";
    public static final String DEFAULT_ERROR_MSG = "系统异常！";
    @ExceptionHandler(value = Exception.class)
    public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
    	String requestType = req.getHeader("X-Requested-With");
    	if("XMLHttpRequest".equals(requestType)){
    		//AJAX 请求
    		Result r = new Result();
        	r.setSuccess(false);
        	r.setMsg(e.getMessage());
        	logger.info("ajax系统异常,{}",e.getMessage());
        	if(logger.isDebugEnabled()){
        		e.getStackTrace();
        	}
            return r;
    	}
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }
}
